package edu.pk.mc.breakthebrick;


import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
//import java.util.Random;

import android.R.color;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;

@SuppressLint("DrawAllocation")
public class GameView extends SurfaceView implements SurfaceHolder.Callback{

	private Context mycontext;
	private int height;
	private int width;
	private Bitmap ball=null;
	private Bitmap paddle=null;
	private Bitmap brick=null;
	private int px;
	private int py;
	private int previousBx,previousBy;
	private int bx,by;
	private List<Brick> bricks;
	private Paint paintText=new Paint(Paint.ANTI_ALIAS_FLAG);
	private int score;
	private int lives;
	Handler handler;
	//private MediaPlayer mp3;
	private class Brick
	{
		int top;
		int left;
		private Bitmap brick;
		private boolean status;
		Brick(Bitmap b,int t,int l,boolean s)
		{
			brick=b;
			top=t;
			left=l;
			status=s;
		}
	}
	public GameView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}
	public GameView(Context context,AttributeSet attr)
	{
		super(context,attr);
		this.mycontext=context;
		getHolder().addCallback(this);
		setBackgroundResource(R.drawable.bg);
		ball = BitmapFactory.decodeResource(getResources(), R.drawable.ball);
		paddle = BitmapFactory.decodeResource(getResources(), R.drawable.paddle);
		brick = BitmapFactory.decodeResource(getResources(), R.drawable.brick3);
		//mp3=MediaPlayer.create(GameView.this,R.)
		score=0;
		lives=3;
		initMe();
		
	}
	private void initMe()
	{
	    handler = new Handler();
	}
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		// TODO Auto-generated method stub
        width = MeasureSpec.getSize(widthMeasureSpec);
        height = MeasureSpec.getSize(heightMeasureSpec);
        paddle = Bitmap.createScaledBitmap(paddle, width/5, height/25, true);
        px = (width - paddle.getWidth()) / 2;
        py = (height - paddle.getHeight())-paddle.getHeight()*2;
        ball=Bitmap.createScaledBitmap(ball, width/15, height/25, true);
        paintText.setColor(color.black);
        paintText.setTextSize(30);
   
        bx=width-ball.getWidth();
        by=height/2;
        previousBx=bx-1;
        previousBy=by+1;
        
        brick=Bitmap.createScaledBitmap(brick,width/10,height/30,true);
        bricks=new ArrayList<Brick>();
        
        for(int j=5; j<height/10; j+=brick.getHeight()+3)
		{
			for(int i=10;i<width-brick.getWidth();i+=brick.getWidth()+3)
			{	
				bricks.add(new Brick(brick,j,i,true));
			}
		}
        setMeasuredDimension(width, height);
        
	}
	int Brick_Collide(List<Brick> arrBricks, int i) {
		  
		  int left1, left2;
		  int right1, right2;
		  int top1, top2;
		  int bottom1, bottom2;
		  
		  left1 = (int)bx;
		  left2 = arrBricks.get(i).left;
		  right1 = (int)bx + ball.getWidth();
		  right2 = arrBricks.get(i).left + brick.getWidth();
		  top1 = (int)by;
		  top2 = arrBricks.get(i).top;
		  bottom1 = (int)by + ball.getHeight();
		  bottom2 = arrBricks.get(i).top + brick.getHeight();
		  
		  if (bottom1 < top2) return(0);
		  if (top1 > bottom2) return(0);
		  
		  if (right1 < left2) return(0);
		  if (left1 > right2) return(0);
		  
		  return(1);
		         };
	Thread t = new Thread(new Runnable() {

		private boolean flag1=false;
		private boolean flag2=false;
		private boolean flag3=false;
		private boolean flag4=false;
		private boolean status=true;
		@Override
		public void run() {
			try{
				while (true)
				{
					int i=0,index=0;
					status=true;
					for( i=0; i<bricks.size() && status;i++)
					{
						if(Brick_Collide(bricks, i) == 1)
						{
							bricks.get(i).status=false;
							//bricks.remove(i);
//							bricks.get(i).left=-100;
//							bricks.get(i).top=-100;
							status=false;
							score+=5;
							index=i;
						}
					}
					///////// right /////////
					if((previousBy<by && bx==0) || (previousBy<by && bx==(bricks.get(index).left)))//+brick.getWidth())) )
					{
						flag2=true;
						flag1=false;
						flag3=false;
						flag4=false;
					}
					else if((previousBy>by && bx==0) || (previousBy>by && bx==(bricks.get(index).left)))//+brick.getWidth())))
					{
						flag4=true;
						flag2=false;
						flag3=false;
						flag1=false;
					}
					/////// left /////////
					if((previousBy<by && bx==(width-ball.getWidth()))||  (previousBy<by && bx==(bricks.get(index).left-ball.getWidth())))
					{
						flag1=true;
						flag4=false;
						flag2=false;
						flag3=false;
					}
					else if((previousBy>by && bx==(width-ball.getWidth()))|| (previousBy>by && bx==(bricks.get(index).left-ball.getWidth())))
					{
						flag3=true;
						flag2=false;
						flag1=false;
						flag4=false;
					}
					////// top ////////
					if((previousBx<bx && by==0) || (previousBx<bx && by==(bricks.get(index).top+brick.getHeight())))
					{
						flag2=true;
						flag4=false;
						flag1=false;
						flag3=false;
					}
					else if((previousBx>bx && by==0) || (previousBx>bx && by==(bricks.get(index).top+brick.getHeight())))
					{
						flag1=true;
						flag2=false;
						flag3=false;
						flag4=false;
					}
					////// bottom ////////
					//(previousBx<bx && by==height-ball.getHeight())
					if( (previousBx<bx && by==py-ball.getHeight()&& (bx>=px && bx<=px+paddle.getWidth())) || (previousBx<bx && by==(bricks.get(index).top-ball.getHeight())))
					{
						flag4=true;
						flag1=false;
						flag2=false;
						flag3=false;
					}
					//(previousBx>bx && by==height-ball.getHeight()) ||
					else if( (previousBx>bx && by==py-ball.getHeight() && (bx>=px && bx<=px+paddle.getWidth()))|| (previousBx>bx && by==(bricks.get(index).top-ball.getHeight())) )
					{
						flag3=true;
						flag1=false;
						flag2=false;
						flag4=false;
					}
					if((previousBx<bx && by==height-ball.getHeight() || previousBx>bx && by==height-ball.getHeight()))
					{
						lives--;
						if(lives!=0)
						{
							handler.post(new Runnable(){
							    public void run(){
							        Toast.makeText(mycontext, "Lives Left: "+lives, Toast.LENGTH_LONG).show();
							    }
							});
						}
						if(lives!=-1)
						{
							flag4=false;
							flag3=true;
							flag2=false;
							flag1=false;
							bx=width-ball.getWidth();
					        by=height/2;
					        previousBx=bx-1;
					        previousBy=by+1;
						}
					}
					if(flag1)
					{
						previousBx=bx;
						previousBy=by;
						bx--;
						by++;
					}
					if(flag2)
					{
						previousBx=bx;
						previousBy=by;
						by++;
						bx++;
					}
					if(flag3)
					{
						previousBx=bx;
						previousBy=by;
						bx--;
						by--;
					}
							
					if(flag4)
					{
						previousBx=bx;
						previousBy=by;
						bx++;
						by--;
					}
					if(!status)
						bricks.remove(index);
//					if(lives==0)
//					{
//						handler.post(new Runnable(){
//						    public void run(){
//						        Toast.makeText(mycontext, "Game Over", Toast.LENGTH_LONG).show();
//						    }
//						});
//						Thread.sleep(3);
//						mycontext=getContext();
//						Intent intent=new Intent(mycontext,MainActivity.class);
//						mycontext.startActivity(intent);
//						//t.interrupt();
//					}
					if(bricks.isEmpty() || lives==0)
					{
						handler.post(new Runnable(){
						    public void run(){
						    	Toast.makeText(mycontext, "Game Over", Toast.LENGTH_LONG).show();
						        Toast.makeText(mycontext, "Your Scores:"+score, Toast.LENGTH_LONG).show();
						    }
						});
						Thread.sleep(3);
						SQLiteDatabase db = new MySQLiteOpenHelper(mycontext).getWritableDatabase();
						ContentValues values = new ContentValues();
						values.put(SQLDemoContract.tables.HighScoreEntry.COLUMN_NAME_SCORE, score);
						db.insert(SQLDemoContract.tables.HighScoreEntry.TABLE_NAME, null, values);
						
						try
				        {
							HttpClient Client = new DefaultHttpClient();
				            String SetServerString = "";
				            
				                    // Create Request to server and get response
				                      String url="http://10.0.2.2:8080/ScoreProject/ScoreInfoServlet?id="+score;
				                      HttpGet httpget = new HttpGet(url);
				                     ResponseHandler<String> responseHandler = new BasicResponseHandler();
				                     SetServerString = Client.execute(httpget, responseHandler);
				           
				                      // Show response on activity 
				                     Toast.makeText(mycontext, "posted to internet", Toast.LENGTH_SHORT).show();
				                     
				         }
				       catch(Exception ex)
				       {
				    	   Toast.makeText(mycontext, "not posted to internet", Toast.LENGTH_SHORT).show();
				           
				       }
						//Toast.makeText(this, "Data inserted", Toast.LENGTH_LONG).show();
						t.interrupt();
						
//						mycontext=getContext();
//						Intent intent=new Intent(mycontext,MainActivity.class);
//						mycontext.startActivity(intent);
						//
						//Toast.makeText(this, "game over", Toast.LENGTH_SHORT);
//						Intent intent=new Intent(mycontext,ScoreScreenActivity.class);
//						intent.putExtra("score", score);
//						mycontext.startActivity(intent);
					}
					
					
					Thread.sleep(5);
					postInvalidate();
				}
			}
			catch (Exception e){
				
			}
		}
		});
	
	PaddleThread thread=new PaddleThread();
	class PaddleThread extends Thread {
		  protected void setBubble(float x, float y) {
			if(x>width-paddle.getWidth())
				px=width-paddle.getWidth();
			else
				px = (int)x;
		  }
	}
	public boolean onTouchEvent(MotionEvent e) {
		   float touchX = e.getX();
		   float touchY = e.getY();
		   switch (e.getAction()) {
		     case MotionEvent.ACTION_DOWN:
		    	 thread.setBubble(touchX, touchY);
		       break;
		     case MotionEvent.ACTION_MOVE:
		    	 thread.setBubble(touchX, touchY);
		         break;
		   }
		   return true;
		 }
	public void onDraw(Canvas canvas)
	{
		super.onDraw(canvas);
		canvas.save();
		canvas.drawBitmap(paddle, px,py,null);
		canvas.restore();
		//canvas.drawText("Score: "+bx+by, 0, height, paintText);
		canvas.save();
		canvas.drawBitmap(ball,bx,by,null);
		canvas.restore();
		canvas.save();
		for(int i = 0 ; i < bricks.size() ; i++)
		{
		    Brick b = bricks.get(i);
		    if(b.status==true)
		    	canvas.drawBitmap(brick,b.left,b.top,null);
		}
		canvas.restore();
		canvas.save();
		canvas.drawText("Score: ", width/2,height/2, paintText);
		canvas.restore();
		invalidate();
	}
	
	@Override
	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void surfaceCreated(SurfaceHolder arg0) {
		// TODO Auto-generated method stub
		t.start();
	}
	@Override
	public void surfaceDestroyed(SurfaceHolder arg0) {
		// TODO Auto-generated method stub
		t.interrupt();
	}
}
